'''

Copyright 2010 Manuel Reinelt

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Created on 12.04.2010

@author: Manuel Reinelt
contact: mrdevlab@googlemail.com

'''
import check_input_file
import crypt_data
import sys
import os
import time

def wipe_file(filename,level,chunksize,verbose):
    
    level = int(level)
       
    def wipe_write(filehandle,data,offset,rounds):
        for i in range(rounds):
            
            if verbose:
                print "writing " + str(len(data)) + " bytes (round " + str(i + 1) + ") at offset " + str(offset)   
                sys.stdout.flush()  
                
            filehandle.seek(offset)
            filehandle.write(data) 
            filehandle.flush()
        
        return filehandle
           
    #check input file:
    filesize, zip = check_input_file.check_input_file(filename,verbose)
    
    wipefile = open(filename,"rb+")
    if verbose:
        print "reading " + filename + " for wiping at level " + str(level)
        sys.stdout.flush()  
    wipefilebuffer = wipefile.read()   
    key = ""
            
    if level == 3:
        if verbose:
            print "generating random 32 byte phrase for aes cipher"
            sys.stdout.flush()  
        key = os.urandom(32)
             
    encdecbytes = ""
    
    for i in range(0,len(wipefilebuffer),chunksize):
        if verbose:
            print "crypting file from " + str(i) + " to " + str(chunksize - 1)
            sys.stdout.flush()  
        if level != 3:
            # for level 1 just fill with 0s:
            encdecbytes = encdecbytes.zfill(len(wipefilebuffer[i:chunksize + i - 1]))
            if level == 2:
                encdecbytes = os.urandom(len(wipefilebuffer[i:chunksize + i - 1]))
        else:
            encdecbytes = crypt_data.crypt_data("aes", key, wipefilebuffer[i:chunksize + i - 1], "enc", verbose)

        offset = i
        if offset == 0:
            offset = -1
            
        wipefile = wipe_write(wipefile,encdecbytes,offset + 1,3)
        
    
    
    if verbose:
        print "deleting wiped file " + filename
        sys.stdout.flush()  
        
        
    wipefile.close()
    os.remove(filename)
    
    
            
            
    
